package cn.jcet;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 鲜磊
 * @Date 2021/1/7 23:32
 */
public class DistributeClient {

    private ZooKeeper zkClient;

    public static void main(String[] args) {
        DistributeClient client = new DistributeClient();
        // 连接
        client.connection();
        // 获取所有节点信息
        client.getChildren();
        // 等待
        client.business();

    }

    private void business() {
        try {
            Thread.sleep(Long.MAX_VALUE);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void getChildren() {
        try {
            List<String> children = zkClient.getChildren("/servers", true);
            // 存储服务列表
            List<String> server = new ArrayList<>();
            if (children != null){
                // 遍历
                for (String child : children) {
                    byte[] data = zkClient.getData("/servers/" + child, false, null);
                    server.add(new String(data));
                }
            }
            System.out.println(server);

        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }

    private void connection() {
        try {
           zkClient =  new ZooKeeper(GetConnection.STRINGCONNECT, GetConnection.SESSIONTIME, new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
                    // 回调监听方法
                    getChildren();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
